package com.andova.camerax

import android.graphics.Matrix
import android.os.Bundle
import android.util.Log
import android.view.TextureView
import android.view.View.*
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.CameraX
import androidx.camera.core.Preview
import androidx.lifecycle.*
import kotlin.math.max
import kotlin.math.min

/**
 * Created by Administrator on 2019-06-13.
 *
 * @author kzaxil
 * @since 1.0.0
 */
class CameraXActivity : LifecycleActivity() {
    private var preview: Preview? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camerax)
    }

    override fun onResume() {
        super.onResume()
//        preview?.apply { CameraX.unbind(preview) }
//        preview = obtainPreview()
//        CameraX.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, preview)
    }

    private fun obtainPreview(): Preview {
        return Preview.Builder()
                .setCameraSelector(CameraSelector.DEFAULT_BACK_CAMERA)
                .build()
//        return Preview(PreviewConfig.Builder().apply {
////            setTargetRotation(Surface.ROTATION_0)
//            setLensFacing(CameraX.LensFacing.BACK)
//        }.build()).apply {
//            setOnPreviewOutputUpdateListener {
//                val w = it.textureSize.width
//                val h = it.textureSize.height
//                with(it) {
//                    Log.i(
//                            TAG,
//                            "OnPreviewOutputUpdateListener onUpdated -> degree:$rotationDegrees, width:$w, height:$h"
//                    )
//                }
//                texture.surfaceTexture = it.surfaceTexture
//                configureTransform(0, w, h, texture)
//            }
//        }
    }

    private fun configureTransform(orientation: Int, width: Int, height: Int, textureView: TextureView) {
        val w = min(width, height).toFloat()
        val h = max(width, height).toFloat()
        val matrix = Matrix()
        if (orientation % 180 == 90) {
            // Rotate the camera preview when the screen is landscape.
            matrix.setPolyToPoly(
                    floatArrayOf(
                            0f, 0f, // top left
                            w, 0f, // top right
                            0f, h, // bottom left
                            w, h
                    )// bottom right
                    , 0,
                    if (orientation == 90)
                    // Clockwise
                        floatArrayOf(
                                0f, h, // top left
                                0f, 0f, // top right
                                w, h, // bottom left
                                w, 0f
                        )// bottom right
                    else
                    // mDisplayOrientation == 270
                    // Counter-clockwise
                        floatArrayOf(
                                w, 0f, // top left
                                w, h, // top right
                                0f, 0f, // bottom left
                                0f, h
                        )// bottom right
                    , 0,
                    4
            )
        } else if (orientation == 180) {
            matrix.postRotate(180f, w / 2, h / 2)
        }
        textureView.setTransform(matrix)
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (!hasFocus) return
        window.decorView.systemUiVisibility = (SYSTEM_UI_FLAG_LAYOUT_STABLE
                or SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or SYSTEM_UI_FLAG_FULLSCREEN
                or SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
    }

    override fun onDestroy() {
        super.onDestroy()
//        CameraX.unbindAll()
    }
}

abstract class LifecycleActivity : AppCompatActivity(), LifecycleOwner {
    private val registry by lazy { LifecycleRegistry(this) }
    override fun getLifecycle(): Lifecycle = registry
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        registry.currentState = Lifecycle.State.CREATED
        registry.addObserver(ActivityLifecycleObserver())
    }

    override fun onStart() {
        super.onStart()
        registry.currentState = Lifecycle.State.STARTED
    }

    override fun onResume() {
        super.onResume()
        registry.currentState = Lifecycle.State.RESUMED
    }

    override fun onDestroy() {
        super.onDestroy()
        registry.currentState = Lifecycle.State.DESTROYED
    }
}

const val TAG = "CameraX"

class ActivityLifecycleObserver : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun create() = Log.i(TAG, "lifecycle onCreate")

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun start() = Log.i(TAG, "lifecycle onStart")

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun resume() = Log.i(TAG, "lifecycle onResume")

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun pause() = Log.i(TAG, "lifecycle onPause")

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stop() = Log.i(TAG, "lifecycle onStop")

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun destroy() = Log.i(TAG, "lifecycle onDestroy")

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun any() = Log.i(TAG, "lifecycle onAny")
}